package medium;

import java.util.ArrayList;
import java.util.List;
/*
54. 螺旋矩阵
解题思路：模拟法
 */
public class LeeCode54 {
  public static void main(String[] args) {
    List<Integer> list = new LeeCode54().spiralOrder(new int[][]{
            {1, 2, 3},
            {8, 9, 4},
            {7, 6, 5}
    });
    for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i));
    }
  }

  public List<Integer> spiralOrder(int[][] matrix) {
    ArrayList<Integer> res = new ArrayList<>();
    int up = 0;
    int down = matrix.length - 1;
    int left = 0;
    int right = matrix[0].length - 1;
    while (true){
      for (int i = left;i <= right;i++){
         res.add(matrix[up][i]);
      }
      if (++up > down){
        break;
      }
      for (int i = up; i <= down; i++) {
        res.add(matrix[i][right]);
      }
      if (--right < left) {
        break;
      }
      for (int i = right; i >= left; i--) {
        res.add(matrix[down][i]);
      }
      if (--down < up) {
        break;
      }
      for (int i = down; i >= up; i--) {
         res.add(matrix[i][left]);
      }
      if (++left > right) {
        break;
      }
    }
    return res;
  }
}
